package com.duckygo.towerdefense.game.sprites;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;

import android.util.Log;
import android.view.MotionEvent;

import com.duckygo.towerdefense.game.TextureManager;
import com.duckygo.towerdefense.game.scenes.SceneManager;

public class Sprite2D extends Sprite {

	public static final int RIGHT = 1;
	
	public static final int LEFT = 2;
	
	public static final int CENTER_HORIZONTAL = 3;

	public static final int TOP = 4;
	
	public static final int BOTTOM = 8;
	
	public static final int CENTER_VERTICAL = 12;
	
	public static final int CENTER = 15;


	
	
	public int anchor = TOP | RIGHT;
	
	public float x;
	
	public float y;
	
	public float z;
	
	public float scaleX = 1;
	
	public float scaleY = 1;
	
	public int width;
	
	public int height;
	
	public float rotation;
	
	public float alpha = 1;
	
	public int texture;

	protected int cropX;

	protected int cropY;
	
	public Sprite2D() {
	}
	
	@Override
	public void draw(GL10 gl) {
		//Log.w("Sprite2D", "Drawing sprite " + texture + " @ " + x + "," + y );
		
		gl.glFrontFace(GL10.GL_CW);
		
		GL11Ext gl1 = (GL11Ext)gl;
		if (alpha != 1)
			gl.glColor4f(alpha, alpha, alpha, alpha);
	
		
		TextureManager.bindTexture(gl, texture, new int[] {cropX, cropY + height, width, - height});
		
		gl1.glDrawTexiOES(getParentX(), SceneManager.HEIGHT - getParentY(), (int)z, (int)(width * scaleX), (int)(height * scaleY));
	}
	
	

	private int getParentX() {
		int x = (int) this.x;
		Sprite2D t = this;
		while (t.parent != null && t.parent instanceof Sprite2D) {
			t = (Sprite2D) t.parent;
			x += t.x;
		}
		
		int offsetX = 0;
		if ((anchor & CENTER_HORIZONTAL) != 0) {
			offsetX  = width / 2;
		} else if ((anchor & RIGHT) != 0) {
			offsetX  = width;
		}
		
		return x - offsetX;
	}

	private int getParentY() {
		int y = (int) this.y;
		Sprite2D t = this;
		while (t.parent != null && t.parent instanceof Sprite2D) {
			t = (Sprite2D) t.parent;
			y += t.y;
		}
		
		int offsetY = 0;
		if ((anchor & CENTER_VERTICAL) != 0) {
			offsetY  = height / 2;
		} else if ((anchor & TOP) != 0) {
			offsetY  = height;
		}

		
		return y + offsetY;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return false;
	}
	
	
	public float getX() {
		return x;
	}

	public void setX(float x) {
		if (parent != null) parent.childrenUpdated = true;
		this.x = x;
	}

	public float getY() {
		return y;
	}

	public void setY(float y) {
		if (parent != null) parent.childrenUpdated = true;
		this.y = y;
	}


}
